<?php
namespace Home\Controller;
use Home\Model\B2cOrdersModel;
use Think\Controller;
use Home\Event\WeixinEvent;
use Home\Event\JssdkEvent;
class FirstController extends Controller {
    //static $error = 0;
    public $app_id;
    public $secret;
    public $wx_url;
    public function __construct(){
        parent::__construct();
        $this->app_id = C('APPID');
        $this->secret = C('SECRET');
        $this->wx_url = C('WX_URL');
    }

    /**
     * 授权(首页)
     */
    public function index(){
        $url = $this->wx_url."Home/First/getLocation.html";

        $url = urlencode($url);
        $getUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri=".$url."&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
        //$getUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri=".$url."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        redirect($getUrl);
    }
    /**
     * 获取token
     */
    public function getLocation(){
        $code = I('code');
        $obj = A('WeixinWeb','Event');
        $data = $obj ->accessToken($code);
        //根据openID查询出会员信息，跳转到默认页面。
        $obj_user = M('b2c_temp_user');

        $user_data = $obj_user -> where(array('openid'=>$data['openid']))->find();
        //如果游客表里面没有，就插入数据库
        if(!$user_data && $data['openid']){
            $user_data = ['source_id'=>1,'nickname'=>$data['nickname'],'openid'=>$data['openid'],'regtime'=>time(),'logo' => $data['headimgurl'],];
            $members_data = [
                'openid' => $data['openid'],
                'nickname' => $data['nickname'],
            ];
            try {
                M()->execute('begin');
                $stat = $obj_user->add($user_data);
                $members_id = M("b2c_members")->add($members_data);
                if ($stat === false || $members_id === false) {
                    throw new \Exception(false);
                }
                M()->execute('commit');
            }catch (\Exception $e){
                M()->execute('rollback');
            }

            session('t_userInfo',$user_data);
            //todo 门店选择
            $this->stortSelect();die;
        }else{
            //以前游客数据存在情况
           $data_member = M('b2c_members')->where(['openid'=>$data['openid']])->find();
           if(!empty($user_data) && empty($data_member) && !empty($data['openid'])){
               if(empty($user_data['default_local_id'])){
                   $user_data['default_local_id'] = 0;
               }
              //为空的情况，插入members数据
               $members_data = [
                   'openid' => $data['openid'],
                   'nickname' => $data['nickname'],
                   'default_local_id' => $user_data['default_local_id'],
                   'status' => '1',
                   'mobile' => $user_data['mobile'],
                   'sex' => '2',
                   'advance' => 0.00,
                   'advance_freeze' => 0.00,
                   'reg_ip' => get_client_ip(),
                   'regtime' => $user_data['regtime'],
               ];
               $stat = M('b2c_members')->add($members_data);
               if($stat === false){
                   return false;
               }
           }

        }
        session('wx_openid',$data['openid']);
        session('t_userInfo',$user_data);
        session('source',1); //微信入口就为1
        //判断是否有默认门店
        if(!$user_data['default_local_id']){
            //dump($user_data);die;
            //todo 门店选择
            $this->stortSelect();die;
        }
        //local_id存入session
        session('home_local_id',$user_data['default_local_id']);
        // todo 有默认门店，进入门店首页 重定向
        $this->redirect('Store/index',['local_id' => $user_data['default_local_id']]);

    }
    /**
     * 授权(个人中心)
     */
    public function user(){
        $url = $this->wx_url."Home/First/getUser.html";
        //$url = "http://m.yichen666.com/Home/First/getUser.html";
        $url = urlencode($url);
        $getUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri=".$url."&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
        redirect($getUrl);
    }
    /**
     * 获取token
     */
    public function getUser(){
        $code = I('code');
        $obj = A('WeixinWeb','Event');
        $data = $obj ->accessToken($code);
        //根据openID查询出会员信息，跳转到默认页面。
        $obj_user = M('b2c_temp_user');
        //dump($data);die;
        $user_data = $obj_user -> where(array('openid'=>$data['openid']))->find();
        //如果游客表里面没有，就插入数据库
        if(!$user_data && $data['openid']){
            $user_data = ['source_id'=>1,'nickname'=>$data['nickname'],'openid'=>$data['openid'],'logo' => $data['headimgurl'],'regtime'=>time()];
            $members_data = [
                'openid' => $data['openid'],
                'nickname' => $data['nickname'],
            ];
            try {
                M()->execute('begin');
                $stat = $obj_user->add($user_data);
                $members_id = M("b2c_members")->add($members_data);
                if ($stat === false || $members_id === false) {
                    throw new \Exception(false);
                }
                M()->execute('commit');
            }catch (\Exception $e){
                M()->execute('rollback');
            }
        }else{
            //以前游客数据存在情况
            $data_member = M('b2c_members')->where(['openid'=>$data['openid']])->find();
            if(!empty($user_data) && empty($data_member) && !empty($data['openid'])){
                if(empty($user_data['default_local_id'])){
                    $user_data['default_local_id'] = 0;
                }
                //为空的情况，插入members数据
                $members_data = [
                    'openid' => $data['openid'],
                    'nickname' => $data['nickname'],
                    'default_local_id' => $user_data['default_local_id'],
                    'status' => '1',
                    'mobile' => $user_data['mobile'],
                    'sex' => '2',
                    'advance' => 0.00,
                    'advance_freeze' => 0.00,
                    'reg_ip' => get_client_ip(),
                    'regtime' => $user_data['regtime'],
                ];
                $stat = M('b2c_members')->add($members_data);
                if($stat === false){
                    return false;
                }
            }

        }
        session('wx_openid',$data['openid']);
        session('t_userInfo',$user_data);
        $letter_obj = new LetterController();
        $ver_status = $letter_obj->verify(1);
        $url = $ver_status === false ? 'Login/index' : 'Member/index';
        // todo 有默认门店，进入门店首页 重定向
        $this->redirect($url);

    }
    /**
     * 授权(购物车)
     */
    public function carts(){
        //$url = "http://weixin.yichen123.cn/Home/First/getCarts.html";
        $url = $this->wx_url."Home/First/getCarts.html";
        $url = urlencode($url);
        $getUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri=".$url."&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
        redirect($getUrl);
    }

    /**
     * 获取token
     */
    public function getCarts(){
        $code = I('code');
        $obj = A('WeixinWeb','Event');
        $data = $obj ->accessToken($code);
        //根据openID查询出会员信息，跳转到默认页面。
        $obj_user = M('b2c_temp_user');

        $user_data = $obj_user -> where(array('openid'=>$data['openid']))->find();
        //如果游客表里面没有，就插入数据库
        if(!$user_data && $data['openid']){
            $user_data = ['source_id'=>1,'nickname'=>$data['nickname'],'openid'=>$data['openid'],'logo' => $data['headimgurl'],'regtime'=>time()];
            $members_data = [
                'openid' => $data['openid'],
                'nickname' => $data['nickname'],
            ];
            try {
                M()->execute('begin');
                $stat = $obj_user->add($user_data);
                $members_id = M("b2c_members")->add($members_data);
                if ($stat === false || $members_id === false) {
                    throw new \Exception(false);
                }
                M()->execute('commit');
            }catch (\Exception $e){
                M()->execute('rollback');
            }
        }else{
            //以前游客数据存在情况
            $data_member = M('b2c_members')->where(['openid'=>$data['openid']])->find();
            if(!empty($user_data) && empty($data_member) && !empty($data['openid'])){
                if(empty($user_data['default_local_id'])){
                    $user_data['default_local_id'] = 0;
                }
                //为空的情况，插入members数据
                $members_data = [
                    'openid' => $data['openid'],
                    'nickname' => $data['nickname'],
                    'default_local_id' => $user_data['default_local_id'],
                    'status' => '1',
                    'mobile' => $user_data['mobile'],
                    'sex' => '2',
                    'advance' => 0.00,
                    'advance_freeze' => 0.00,
                    'reg_ip' => get_client_ip(),
                    'regtime' => $user_data['regtime'],
                ];
                $stat = M('b2c_members')->add($members_data);
                if($stat === false){
                    return false;
                }
            }

        }
        session('wx_openid',$data['openid']);
        session('t_userInfo',$user_data);
        $letter_obj = new LetterController();
        $ver_status = $letter_obj->verify(1);
        $url = $ver_status === false ? 'Login/index' : 'Carts/cart';
        $controller = 'Carts';
        $action = 'cart';
        $url = U($url,['controller'=>$controller,'action'=>$action]);
        // todo 有默认门店，进入门店首页 重定向
        //$this->redirect($url);
        echo "<script language=\"javascript\">";
        echo "location.href=\"$url\"";
        echo "</script>";

    }


    /**
     * 授权(分销页面)
     */
    public function chooseShop(){
        $url = $this->wx_url."Home/First/getChooseShop.html";
        $url = urlencode($url);
        $getUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri=".$url."&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
        redirect($getUrl);
    }


    /**
     * 获取token
     */
    public function getChooseShop(){
        $code = I('code');
        $obj = A('WeixinWeb','Event');
        $data = $obj ->accessToken($code);
        //根据openID查询出会员信息，跳转到默认页面。
        $obj_user = M('b2c_temp_user');

        $user_data = $obj_user -> where(array('openid'=>$data['openid']))->find();
        //如果游客表里面没有，就插入数据库
        if(!$user_data && $data['openid']){
            $user_data = ['source_id'=>1,'nickname'=>$data['nickname'],'openid'=>$data['openid'],'logo' => $data['headimgurl'],'regtime'=>time()];
            $members_data = [
                'openid' => $data['openid'],
                'nickname' => $data['nickname'],
            ];
            try {
                M()->execute('begin');
                $stat = $obj_user->add($user_data);
                $members_id = M("b2c_members")->add($members_data);
                if ($stat === false || $members_id === false) {
                    throw new \Exception(false);
                }
                M()->execute('commit');
            }catch (\Exception $e){
                M()->execute('rollback');
            }
        }else{
            //以前游客数据存在情况
            $data_member = M('b2c_members')->where(['openid'=>$data['openid']])->find();
            if(!empty($user_data) && empty($data_member) && !empty($data['openid'])){
                if(empty($user_data['default_local_id'])){
                    $user_data['default_local_id'] = 0;
                }
                //为空的情况，插入members数据
                $members_data = [
                    'openid' => $data['openid'],
                    'nickname' => $data['nickname'],
                    'default_local_id' => $user_data['default_local_id'],
                    'status' => '1',
                    'mobile' => $user_data['mobile'],
                    'sex' => '2',
                    'advance' => 0.00,
                    'advance_freeze' => 0.00,
                    'reg_ip' => get_client_ip(),
                    'regtime' => $user_data['regtime'],
                ];
                $stat = M('b2c_members')->add($members_data);
                if($stat === false){
                    return false;
                }
            }

        }
        session('wx_openid',$data['openid']);
        session('t_userInfo',$user_data);
        $letter_obj = new LetterController();
        $ver_status = $letter_obj->verify(1);
        $url = $ver_status === false ? 'Login/index' : 'Member/chooseShop';
        $controller = 'Member';
        $action = 'chooseShop';
        $url = U($url,['controller'=>$controller,'action'=>$action]);
        // todo 有默认门店，进入门店首页 重定向
        //$this->redirect($url);
        echo "<script language=\"javascript\">";
        echo "location.href=\"$url\"";
        echo "</script>";
    }

    /**
     * 门店选择
     * $source 1-微信、0-其他渠道
     */
   /* public function stortSelect(){

        $source = session('source');
        $ak = C('BAIDU_AK');
        $jssdk = A('Jssdk','Event');
        $local_id = I('local_id');
        if($local_id || is_numeric($local_id)){
            $data = M('webpos_local_store')->where(['local_id'=>$local_id])->find();
            $this->assign('lbs',1);//有默认门店，且在区域中不定位
            $this->assign('data',$data);
        }
        $signPackage = $jssdk->GetSignPackage();
        //查询店铺所属区域传到页面上
        $this->assign(['signPackage' => $signPackage]);
        $this->assign(['ak' => $ak]);
        $this->assign('source',$source);
        $this->display('location');
    }*/
    public function stortSelect(){
        $source = session('source');
        $ak = C('BAIDU_AK');
        $jssdk = A('Jssdk','Event');
        $local_id = I('local_id');
        if($local_id || is_numeric($local_id)){
            $data = M('webpos_local_store')->where(['local_id'=>$local_id])->find();
            //dump($data);
            $store = $this->checkStore($data['province'],$data['city'],$data['area']);
            $this->assign('data',$data);
            $this->assign('store',$store);
        }
        $signPackage = $jssdk->GetSignPackage();
        //查询店铺所属区域传到页面上
        $this->assign(['signPackage' => $signPackage]);
        $this->assign(['ak' => $ak]);
        $this->assign('source',$source);
        $this->display('location');
    }

    /**
     * 选择门店后
     */
    public function doStortSelect(){
        $local_id = I('get.local_id') or $this->error('参数错误！');
        if(!is_numeric($local_id)){
            $this->error('参数错误！');
        }
        //dump($local_id);die;
        $t_uid = session('t_userInfo')['t_u_id'];

        $stat = M('b2c_temp_user')->where(array('t_u_id' => $t_uid))->save(['default_local_id' => $local_id]);
        if($stat === false){
            $this->error('切换门店失败！');
        }
        session('home_local_id',$local_id);
        $userdata = M('b2c_temp_user')->where(array('t_u_id' => $t_uid))->find();
        session('t_userInfo',$userdata);
        $this->redirect('Store/index',['local_id' => $local_id]);
    }

    /**
     * 地区
     */
    public function regions(){
        exit(regions());
    }

    /**
     * 根据经纬度查询市区的所有门店
     */
    /*public function seatStortSelect(){
        $data = [];
        if(!I('lng') || !is_numeric(I('lng'))){
            $data['error'] = false;
            $data['msg'] = '经度不对！';
            exit(json_encode($data));
        }
        $lng = I('lng');//经度

        if(!I('lat') || !is_numeric(I('lat'))){
            $data['error'] = false;
            $data['msg'] = '纬度不对！';
            exit(json_encode($data));
        }
        $lat = I('lat');//纬度

        if(!I('province')){
            $data['error'] = false;
            $data['msg'] = '省区地址不对！';
            exit(json_encode($data));
        }
        $province = I('province');//省
        if(!I('city')){
            $data['error'] = false;
            $data['msg'] = '市区地址不对！';
            exit(json_encode($data));
        }
        $city = I('city');//市区
        //查询市区里的所有门店
        $data = $this->checkStore($province,$city,$district,$lng,$lat);
        //dump($data);
        exit(json_encode($data));
    }*/

    /**
     * 判断用户位置当前最近的门店是否是默认门店
     */
    public function rankStore(){
        if(!I('lng') || !is_numeric(I('lng'))){
            $data['error'] = false;
            $data['msg'] = '经度不对！';
            exit(json_encode($data));
        }
        $lng = I('lng');//经度

        if(!I('lat') || !is_numeric(I('lat'))){
            $data['error'] = false;
            $data['msg'] = '纬度不对！';
            exit(json_encode($data));
        }
        $lat = I('lat');//纬度
    }

    /**
     * 根据省市区查询门店
     */
    public function placeStortSelect(){
        $data = [];

        $lng = I('lng') ? I('lng') : 0;//经度
        $lat = I('lat') ? I('lat') : 0;//纬度
        if(!I('province')){
            $data['error'] = false;
            $data['msg'] = '省区地址不对！';
            exit(json_encode($data));
        }
        $province = I('province');//省
        if(!I('city')){
            $data['error'] = false;
            $data['msg'] = '市区地址不对！';
            exit(json_encode($data));
        }
        $city = I('city');//区县
         if(!I('district')){
             $data['error'] = false;
             $data['msg'] = '区县地址不对！';
             exit(json_encode($data));
         }
        $district = I('district');//区县
        //查询区县的所有门店
        $data = $this->checkStore($province,$city,$district,$lng,$lat);

        //dump($data);
        exit(json_encode($data));
    }

    /**
     * 根据省市区查询周边门店，如有经纬度就排序
     * @param $province 省
     * @param $city 市
     * @param $district 区
     * @param int $lng 经度
     * @param int $lat 纬度
     * @return mixed
     */
    public function checkStore($province,$city,$district,$lng = 0,$lat = 0){
        //加上门店  local_status  只显示  正在营业的门店
        $data = M('webpos_local_store')->where(['province'=>$province,'city'=>$city,'area'=>$district,'is_self' => ['neq',1], 'local_status' => '1'])->select();
        //有经纬度的时候排序
        if($lng && $lat){
            if(!is_numeric($lng) || !is_numeric($lat)){
                $data['error'] = false;
                $data['msg'] = '参数错误！';
                exit(json_encode($data));
            }
            $distance = [];
            //根据经纬度排序
            foreach($data as $k1 => $v1){
                //勾股定理计算出两经纬度的直线距离
                $data[$k1]['distance'] = getDistance($v1['store_lnt'], $v1['store_lat'], $lng, $lat);
                $distance[] = $data[$k1]['distance'];
            }
            array_multisort($distance,SORT_ASC,SORT_NUMERIC,$data);
        }
        return $data;
    }

    public function skipStortSelect(){
        $loca_id = I('local_id',0,'intval');
        if(!$loca_id){
            $this->error('参数错误!');
        }
        session('stortSelect',1);
        //看是否有游客信息
        $t_userInfo = session('t_userInfo');
        if($t_userInfo['openid']){
            //修改默认店铺
            M('b2c_temp_user')->where(array('openid'=>$t_userInfo['openid']))->save(['default_local_id'=>$loca_id]);
        }
        //local_id存入session
        session('local_id',$loca_id);
        $this->redirect('Store/index', array('local_id' => $loca_id));
    }

    /**
     * 微信推送消息链接（订单详情）
     */
    public function wxOrdetails(){
        $order_id = I('get.order_id');
        $member_id = I('get.member_id');
        //dump($order_id);die;
        if(!$order_id || !is_numeric($order_id)){
            $this->error('参数不对！');
        }
        $obj_order = new B2cOrdersModel();
        //$addr_data = M('b2c_member_addrs')->where(['member_id' => $member_id,'def_addr' => 1])->find();
        $order_data = $obj_order->alias('o')
            ->field("o.*,d.logi_name,d.logi_no,s.tel,s.local_log,m.nickname,m.mobile")
            ->join("left join ".C('DB_PREFIX')."b2c_delivery d on o.order_id = d.order_id")
            ->join("left join ".C('DB_PREFIX')."webpos_local_store s on s.local_id = o.local_id")
            ->join("left join ".C('DB_PREFIX')."b2c_members m on m.member_id = o.member_id")
            ->where(['o.order_id' => $order_id])->find();
        //echo $this->obj_order->_sql();
        //dump($order_data);die;
        $data = $obj_order->orderDetail($order_id);
        $this->assign('orderId',$order_id);
        //$this->assign('addr_data',$addr_data);
        $this->assign('order_data',$order_data);
        $this->assign('data',$data);
        $this->display();
    }

    /**
     * 公用授权
     */
    public function publicBase(){

        $code = I('code');
        /*$controller = I('controller') ? I('controller') : 'Store';
        $action = I('action') ? I('action') : 'index';
        $local_id = I('local_id',0);
        $id = I('id',0);*/
        $return_url = I('get.return_url');
        $return_url = urldecode($return_url);

        $obj = A('WeixinWeb','Event');
        $data = $obj ->accessToken($code);
        //根据openID查询出会员信息，跳转到默认页面。
        $obj_user = M('b2c_temp_user');
        $user_data = $obj_user -> where(array('openid'=>$data['openid']))->find();

        //如果游客表里面没有，就插入数据库
        if(empty($user_data) && !empty($data['openid'])){
            $user_data = ['source_id'=>1,'nickname'=>$data['nickname'],'openid'=>$data['openid'],'regtime'=>time(),'logo' => $data['headimgurl'],'is_url_add' => 2];
            $members_data = [
                'openid' => $data['openid']
            ];

            try {
                M()->execute('begin');
                $stat = $obj_user->add($user_data);

                $members_id = M("b2c_members")->add($members_data);
                if ($stat === false || $members_id === false) {
                    throw new \Exception(false);
                }
                M()->execute('commit');
            }catch (\Exception $e){
                M()->execute('rollback');
            }
        }

        session('wx_openid',$data['openid']);
        session('t_userInfo',$user_data);
//        file_put_contents('c.txt', $return_url);
        header("Location: $return_url");die;
        //$this->redirect($return_url);
    }

    /**
     * 通用参数（前端需要）
     */
    public function appId(){
        $jssdk = new JssdkEvent();
        $signPackage = $jssdk->GetSignPackage();
        if(!empty($signPackage)){
            $this->ajaxReturn(['status'=>true,'signPackage'=>$signPackage]);
        }
        $this->ajaxReturn(['status'=>false,'msg'=>'未获取到!']);
    }

    /**
     * 取消切换门店
     */
    public function cancelStort()
    {
        session('stortSelect',1);
        exit(json_encode(true));
    }

   

}